/*
 * $Id: MixedDomStreamReader.java,v 1.2 2009/07/24 18:34:01 oliver Exp $
 *
 * Copyright (C) 2006 General Electric Company. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of the General
 * Electric Company (GE). You shall not disclose this software and shall use it
 * only in accordance with the terms of the license agreement you entered into
 * with GE.
 *
 * GE MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
 * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. GE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING, OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES.
 */

package org.simplx.xstream;

import com.thoughtworks.xstream.io.xml.DomReader;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.Arrays;
import java.util.Iterator;

/**
 * A reader that manages mixed text and nodes in an XML stream.
 *
 * @author Ken Arnold
 */
public class MixedDomStreamReader extends DomReader
        implements MixedStreamReader {

    /**
     * Creates a new {@link MixedDomStreamReader}.
     *
     * @param elem The element at the top of the subtree of XML that is managed
     *             by this reader.
     */
    public MixedDomStreamReader(Element elem) {
        super(elem);
    }

    public Iterator partIterator() {
        Node elem = (Node) getCurrent();
        NodeList kids = elem.getChildNodes();
        Object[] parts = new Object[kids.getLength()];
        for (int i = 0; i < kids.getLength(); i++) {
            final Node child = kids.item(i);
            if (child instanceof Element) {
                parts[i] = new NodePart() {
                    public String nodeName() {
                        return child.getNodeName();
                    }
                };
            } else {
                parts[i] = new TextPart() {
                    public String contents() {
                        return child.getTextContent();
                    }
                };
            }
        }
        return Arrays.asList(parts).iterator();
    }
}
